(function(){
	var winW = screen.width;
	var winH = screen.height;
	var u = navigator.userAgent;
	var cw = document.documentElement.clientWidth;
	var ch = document.documentElement.clientHeight;
	
	var gameWraper = document.getElementById('game-wraper');
	var bgt = document.getElementById('bg-t');
	var bg = document.getElementById('bg');
	var ad = document.getElementById('ad');

	var gameStart = document.getElementById('game-start');
	var start1 = document.getElementById('start1');
	var start2 = document.getElementById('start2');
	var btns = document.getElementById('btns');
	var btn = document.getElementById('btn');

	var gameOver = document.getElementById('game-over');
	var gameReset = document.getElementById('game-reset');
	var Container = document.getElementById('Container');
	var gameContainer = document.getElementById('gameContainer');
	
	
	// var conclusion = document.getElementById('conclusion');
	var mask = document.getElementById('mask');
	var sharebg = document.getElementById('sharebg');
	var shareBtn = document.getElementById('share-btn');

	var messi = document.getElementById('messi');
	var nylmar = document.getElementById('nylmar');

	var failure1 = document.getElementById('failure1');
	var failure2 = document.getElementById('failure2');
	var victory11 = document.getElementById('victory1-1');
	var victory12 = document.getElementById('victory1-2');
	var victoryTxt1 = document.getElementById('victory-txt1');
	var victory21 = document.getElementById('victory2-1');
	var victory22 = document.getElementById('victory2-2');
	var victoryTxt2 = document.getElementById('victory-txt2');


	var victory2 = document.getElementById('victory2');
	var overBox = document.getElementById('over-box');

	var  succeed = '我已成功挑战球神，请小伙伴们为我点赞！！！';
	var  fail = '我没有挑战成功球神，谁来帮个忙？？？';
	var  victory = '', currentSpriteType;

	var showtime = 500;

	// app下载
	var download = 'http://ifeng.fm/index.php/index/download';
	ad.addEventListener('click', function() {
		var url = location.href;
		location.href = download;	
	});

	// 开始按钮
	btn.addEventListener('click', startFn, false);
	btn.addEventListener('touchstart', null, false);

	function startFn(event) {

		var w = this.offsetWidth  / 2, x;
		var touches = event.changedTouches || event.touches;
		touches ? x = touches[0].pageX : x = event.offsetX;
		if(x < w) {
			gameStart.style.display = 'none';
			setImg(GameApp.MESSI);
		}
		else {
			gameStart.style.display = 'none';
			setImg(GameApp.NYLMAR);
		}
		ad.style.visibility = 'visible';
	}

	// 游戏结束弹层
	function showGameOver(n) {
		var adt = 0, txtt = 30, vt = 0;
		screen.height == 480 ? t = 20 : t = 80;
		screen.height == 480 ? vt = 0 : vt = 60;
		gameOver.style.display ='block';
		failure1.style.display = 'none';
		failure2.style.display = 'none';
		victory1.style.display = 'none';	
		victory2.style.display = 'none';	
		mask.style.display = 'none';

		if(n == 1) {
			if(currentSpriteType == GameApp.MESSI) {
				victory1.style.display = 'block';
				victory1.style.top = vt + 'px';

				victory = shareTitle = '我用' + GameApp.step + '步围住了球神！！';	
				victoryTxt1.style.left = victory12.offsetLeft + txtt + 'px';
				victoryTxt1.style.top = victory12.offsetTop + 'px';
				
				overBox.style.top = victory1.offsetHeight + overBox.offsetHeight + t + 'px';

				victoryTxt1.innerHTML = '我用<span class="c1">' + GameApp.step + '</span>步围住了球神！！';
			}
			else if(currentSpriteType == GameApp.NYLMAR) {
				victory2.style.display = 'block';
				victory2.style.top = vt + 'px';

				victory = shareTitle = '我用' + GameApp.step + '步围住了球神！！';	
				victoryTxt2.style.left = victory22.offsetLeft + txtt + 'px';
				victoryTxt2.style.top = victory22.offsetTop + 'px';

				victoryTxt2.innerHTML = '我用<span class="c1">' + GameApp.step + '</span>步围住了球神！！';

				overBox.style.top = victory2.offsetHeight + overBox.offsetHeight + t  + 'px';
			}
			descContent = succeed;

			document.title = shareTitle + succeed;
		}
		else if(n == 0) {
			if(currentSpriteType == GameApp.MESSI) {
				failure1.style.display = 'block';	
				if(screen.height == 480) {
					overBox.style.top = failure1.offsetHeight + overBox.offsetHeight  + 'px';		
				}
				else {
					failure1.style.top = 70 + 'px';

					overBox.style.top = failure1.offsetHeight + overBox.offsetHeight + 40  + 'px';	
				}
				failure1.style.left = (Container.offsetWidth - failure1.offsetWidth) / 2 + 2 + 'px';
			}
			else if(currentSpriteType == GameApp.NYLMAR) {
				failure2.style.display = 'block';
				if(screen.height == 480) {
					overBox.style.top = failure2.offsetHeight + overBox.offsetHeight  + 'px';
				}
				else {
					failure2.style.top = 70 + 'px';
					overBox.style.top = failure2.offsetHeight + overBox.offsetHeight + 40  + 'px';	
				}
				failure2.style.left = (Container.offsetWidth - failure2.offsetWidth) / 2 + 2 + 'px';
			}

			descContent = fail;
			shareTitle = '挑战球神失手！！！';
			document.title = shareTitle + fail;
		}

		mask.style.display = 'block';

		
		gameReset.addEventListener('click', replay, false);

		function replay() {
			gameOver.style.display = 'none';
			mask.style.display = 'none';
			GameApp.init();
		}
	}

	// 通知好友
	shareBtn.addEventListener('click', share, false);
	function share(){
		sharebg.style.display = 'block';
		setTimeout(function(){
			sharebg.style.display = 'none';
		}, 3000);
	}

	var NAME = {
		MESSI: '梅西',
		NYLMAR: '内马尔'
	};

	// 设置人物图片路径
	function setImg(type) {
		var img = document.getElementById('image');
		if(type == GameApp.MESSI) {
			img.src = 'img/01.gif';
			currentSpriteType = GameApp.MESSI;
		}
		else if(type == GameApp.NYLMAR) {
			img.src = 'img/02.gif';
			currentSpriteType = GameApp.NYLMAR;
		}
	}


	// 圆点的间距
	var sta = 7, m = 4, pix = 20;

	if(screen.width == 320 && screen.height == 480) {
		m = 4;
		sta = 6;
		pix = 13;
	}

	else if(screen.width == 320 && screen.height != 480) {
		m = 3;
		sta = 5;
		pix = 13;
	}
	else if(screen.width == 480) {
		m = 4;
		sta = 6;
		pix = 13;
	}

	// 创建圆点对象
	function Sprite(sprite) {
		// var cw = bg.offsetWidth, ch = bg.offsetHeight; 
		var cw = Container.offsetWidth, ch = Container.offsetHeight; 
		var cs = cw / 9 - sta;
		this.setSpriteType = function(type, flag) {
			this.spriteType = type;
			switch(type) {
				case GameApp.DEFAULTS :
					this.setColor('#c4c4c4', flag);
					break;
				case GameApp.PAST :
					this.setColor('#3db44a', flag);
					break;
			}
		}	

		this.setColor = function(colorString, flag) {
			sprite.className = 'sprite';
			sprite.style.background = colorString;
			if(flag) {
				sprite.style.width = cs + 'px';
				sprite.style.height = cs + 'px';
				sprite.style.borderRadius = cs + 'px';
				sprite.style.marginLeft = m + 'px';
				// 相对于小屏幕做稍微调整
				if((screen.width == 320 && screen.height == 480) || (screen.width == 480  && screen.height == 854)) {
					sprite.style.marginBottom = m - 1 + 'px';
				}
				else {
					sprite.style.marginBottom = m + 'px';
				}	
			}
		}

		this.setPos = function(sprite, elem) {
			elem.style.left = sprite.obj.left + 'px'; 
			elem.style.top = sprite.obj.top + 'px'; 
		}

		this.getSpriteType = function() {
			return this.spriteType;
		}

		this.setSpriteType(GameApp.DEFAULTS, true);
	}

	// dom碎片对象
	var oFrag1 = document.createDocumentFragment();

	// 游戏对象
	var GameApp = {
		// 精灵
		DEFAULTS: 1,
		PAST: 2,
		MESSI: 3,
		NYLMAR: 4,
		//方向
		MOVE_NONE: -1, 
		MOVE_LEFT: 0, 
		MOVE_TOP_LEFT: 1, 
		MOVE_TOP_RIGHT: 2, 
		MOVE_RIGHT: 3, 
		MOVE_DOWN_RIGHT: 4, 
		MOVE_DOWN_LEFT: 5,

		container: document.getElementById('Container'),
		spriteArr: [[], [], [], [], [], [], [], [], []],
		currentSprite: null,
		currentSpriteType: -1,
		step: 0,
		
		init: function() {
			var children = GameApp.container.getElementsByTagName('div');
			GameApp.container.innerHTML = '';
			this.currentSpriteType = currentSpriteType || this.MESSI;
			this.step = 0;
			//随机填充为走过的路
				this.selectedArr = [0.12, 0.34];
				this.selectedNum = this.selectedArr[parseInt(Math.random() * this.selectedArr.length)];

			this.addSprites();
			setImg(this.currentSpriteType);
		},
		// 获取方向
		getDirection: function (sprite) {
			var distanceMap = [], can, x, y;
	        window.distanceMap = distanceMap;
	        window.testArr = [];
			// left
			can = true;
			for(var x = sprite.obj.indexX; x >= 0; x--) {
				if(GameApp.spriteArr[x][sprite.obj.indexY].obj.getSpriteType() == GameApp.PAST) {
					can = false;
					distanceMap[GameApp.MOVE_LEFT] = sprite.obj.indexX - x;
					testArr.push(sprite.obj.indexX - x);
					break;
				}
			}
			if(can) { return GameApp.MOVE_LEFT;}
			// up left
			can = true;
			x = sprite.obj.indexX;
 			y = sprite.obj.indexY;
 			while (true) {
	            if (GameApp.spriteArr[x][y].obj.getSpriteType() == GameApp.PAST) {
	                can = false;
	                distanceMap[GameApp.MOVE_TOP_LEFT] = sprite.obj.indexY - y;
	                testArr.push(sprite.obj.indexY - y);
	                break;
	            }

	            if (y % 2 == 0) {
	                x--;
	            }
	            y--;
	            if (y < 0 || x < 0) {
	                break;
	            }
	        }
 			if(can) { return GameApp.MOVE_TOP_LEFT; }

 			// left bottom
 			can = true;
 			x = sprite.obj.indexX;
 			y = sprite.obj.indexY;
	        while (true) {
	            if (GameApp.spriteArr[x][y].obj.getSpriteType() == GameApp.PAST) {
	                can = false;
	                distanceMap[GameApp.MOVE_DOWN_LEFT] = y - sprite.obj.indexY;
	                testArr.push(y - sprite.obj.indexY);
	                break;
	            }

	            if (y % 2 == 0) {
	                x--;
	            }
	            y++;
	            if (y > 8 || x < 0) {
	                break;
	            }
	        }
	        if (can) { return GameApp.MOVE_DOWN_LEFT; }

	        // right 
 			can = true;
 			for (var i = sprite.obj.indexX; i < 9; i++) {
	            if (GameApp.spriteArr[i][sprite.obj.indexY].obj.getSpriteType() == GameApp.PAST) {
	                can = false;
	                distanceMap[GameApp.MOVE_RIGHT] = i - sprite.obj.indexX;
	                testArr.push(i - sprite.obj.indexX);
	                break;
	            }
	        }
	        if (can) { return GameApp.MOVE_RIGHT; }
			

			// right top
 			can = true;
 			x = sprite.obj.indexX;
 			y = sprite.obj.indexY;
	        while (true) {
	            if (GameApp.spriteArr[x][y].obj.getSpriteType() == GameApp.PAST) {
	                can = false;
	                distanceMap[GameApp.MOVE_TOP_RIGHT] = sprite.obj.indexY - y;
	                testArr.push(sprite.obj.indexY - y);
	                break;
	            }

	            if (y % 2 == 1) {
	                x++;
	            }
	            y--;

	            if (y < 0 || x > 8) {
	                break;
	            }
	        }
	        if (can) { return GameApp.MOVE_TOP_RIGHT }

			// right down
			can = true;
			x = sprite.obj.indexX;
			y = sprite.obj.indexY;
	        while (true) {
	            if (GameApp.spriteArr[x][y].obj.getSpriteType() == GameApp.PAST) {
	                can = false;
	                distanceMap[GameApp.MOVE_DOWN_RIGHT] = y - sprite.obj.indexY;
	                testArr.push(y - sprite.obj.indexY);
	                break;
	            }

	            if (y % 2 == 1) {
	                x++;
	            }
	            y++;

	            if (y > 8 || x > 8) {
	                break;
	            }
	        }
	        if (can) { return GameApp.MOVE_DOWN_RIGHT; }	       

	   
	        var maxDir = -1, maxValue = -1;
	        for (var dir = 0; dir < distanceMap.length; dir++) {
	        	// console.log('distanceMap:' + distanceMap, '---maxValue:'+ maxValue);
	            if (distanceMap[dir] && distanceMap[dir] > maxValue) {
	                maxValue = distanceMap[dir];
	                maxDir = dir;
	            }
	        }
	        
	        if (maxValue > 1) {
	            return maxDir;
	        } else {
	            return GameApp.MOVE_NONE;
	        }

		},

		// 点击方法
		spriteClicked: function(e) {
			var target = e.target.inversed.obj;
			if(target.left == GameApp.currentSprite.obj.left && target.top == GameApp.currentSprite.obj.top) return;
			if(GameApp.currentSprite.obj.indexX == 0 || GameApp.currentSprite.obj.indexY == 0 || GameApp.currentSprite.obj.indexX == 8 || GameApp.currentSprite.obj.indexY == 8) {
				setTimeout(function(){
					showGameOver(0)
				}, showtime);
				return;
			}

			if(target.getSpriteType() == GameApp.DEFAULTS) {
				target.setSpriteType(GameApp.PAST);
			}
			else {
				return;
			}
			

			GameApp.step++;

			var dir = GameApp.getDirection(GameApp.currentSprite);
			
			target.setSpriteType(GameApp.PAST);

			switch (dir) {
				case GameApp.MOVE_LEFT :
					GameApp.currentSprite = GameApp.spriteArr[GameApp.currentSprite.obj.indexX - 1][GameApp.currentSprite.obj.indexY];
				break;
				case GameApp.MOVE_TOP_LEFT :
					GameApp.currentSprite = GameApp.spriteArr[GameApp.currentSprite.obj.indexY % 2 ? GameApp.currentSprite.obj.indexX : GameApp.currentSprite.obj.indexX - 1][GameApp.currentSprite.obj.indexY - 1];
				break;
				case GameApp.MOVE_DOWN_LEFT :
	                GameApp.currentSprite = GameApp.spriteArr[GameApp.currentSprite.obj.indexY % 2 ? GameApp.currentSprite.obj.indexX : GameApp.currentSprite.obj.indexX - 1][GameApp.currentSprite.obj.indexY + 1];
                break;

                case GameApp.MOVE_RIGHT :
	                GameApp.currentSprite = GameApp.spriteArr[GameApp.currentSprite.obj.indexX + 1][GameApp.currentSprite.obj.indexY];
                break;
                case GameApp.MOVE_TOP_RIGHT :
	                GameApp.currentSprite = GameApp.spriteArr[GameApp.currentSprite.obj.indexY % 2 ? GameApp.currentSprite.obj.indexX + 1 : GameApp.currentSprite.obj.indexX][GameApp.currentSprite.obj.indexY - 1];
                break;
                case GameApp.MOVE_DOWN_RIGHT :
	                GameApp.currentSprite = GameApp.spriteArr[GameApp.currentSprite.obj.indexY % 2 ? GameApp.currentSprite.obj.indexX + 1 : GameApp.currentSprite.obj.indexX][GameApp.currentSprite.obj.indexY + 1];
                break
 				case GameApp.MOVE_NONE:
 					setTimeout(function(){
 						showGameOver(1);
 					}, showtime);
				break;
			}
			GameApp.currentSprite.obj.setPos(GameApp.currentSprite, sp);
		},

		// 添加精灵
		addSprites: function() {
			var img;
			for (var y = 0; y < 9; y++) {
				for(var x = 0; x < 9; x++) {
					var sprite = document.createElement('div');
					sprite.setAttribute('data-x',x);
					sprite.setAttribute('data-y',y);
					// 创建div
					sprite.obj = new Sprite(sprite);
					oFrag1.appendChild(sprite);
		
					// 添加到场景
					this.container.appendChild(oFrag1);
					
					// 存储所有圆点对象 和 xy坐标
					this.spriteArr[x][y] = sprite;
					sprite.obj.indexX = x;
					sprite.obj.indexY = y;	

					// 设置偶数行向右偏
					if(y % 2) {
						sprite.style.left = (sprite.offsetLeft + pix) + 'px';
						sprite.obj.left = (sprite.offsetLeft + pix);
					}
					else {
						sprite.style.left = sprite.offsetLeft + 3 + 'px';
						sprite.obj.left = sprite.offsetLeft + 3;
					}
					sprite.style.top = sprite.offsetTop + 'px';
					sprite.obj.top = sprite.offsetTop;

					//设置主角位置
					if(x == 4 && y == 4) {
						var spelem = document.getElementById('rs');
						if(!spelem) {
							img = document.createElement('img');
							sp = document.createElement('div');
							img.id = 'image';
							sp.id = 'sp';
							sp.className = 'sp';
							// 设置图片宽度
							if(sprite.offsetWidth <= 33 || sprite.offsetHeight <= 33) {
								img.width = 38;
							}
							else {
								img.width = 50;
							}

							sp.appendChild(img);
							this.container.appendChild(sp);
						}
				
						sprite.obj.setPos(sprite, sp);
						
						this.currentSprite = sprite;
						// this.currentSpriteType = type;
					}
					else if(Math.random() < this.selectedNum) {
						sprite.obj.setSpriteType(this.PAST, 1);
					}
					
					sprite.addEventListener('click', this.spriteClicked, false);
					sprite.addEventListener('touchstart', this.spriteClicked, false);
					sprite.addEventListener('touchmove', function(){return false}, false);
					sprite.addEventListener('touchend', this.spriteClicked, false);
				}
			}
			gameContainer.innerHTML = this.container.innerHTML;


			var children = this.container.getElementsByTagName('div');
			var children1 = gameContainer.getElementsByTagName('div');
			for(var i = 0; i < children.length; i++) {
				children[i].style.position = 'absolute';
				children[i].style.margin = '0';
			}
			for(var i = 0; i < children1.length; i++) {

				children1[i].style.position = 'absolute';
				children1[i].style.margin = '0';
				if(children1[i].id != 'sp') {
					children1[i].inversed = children[i];
					children1[i].addEventListener('click', this.spriteClicked, false);
					children1[i].addEventListener('touchstart', this.spriteClicked, false);
					children1[i].addEventListener('touchmove', function(){return false}, false);
					children1[i].addEventListener('touchend', this.spriteClicked, false);
				}
				else {
					children1[i].removeChild(children1[i].getElementsByTagName('img')[0]);
				}
			}
		
			var image = document.getElementById('image');
			if(sprite.offsetWidth <= 33) {
				image.style.left = -2 + 'px';
				image.style.top = -28 + 'px';
			}
			else {
				image.style.left = -2 + 'px';
				image.style.top = -34 + 'px';
			}
			
		}
	};

	// 初始化游戏
	var mtop = 25;

	//初始化背景图和游戏层宽高
	if(u.indexOf('iPhone') != -1 || u.indexOf('Android') != -1) {
		children = gameContainer.getElementsByTagName('div');

		gameWraper.style.width = cw + 'px';
		gameWraper.style.height = ch  + 'px';

		gameWraper.style.backgroundSize =  cw + 'px';

		gameStart.style.width = cw + 'px';

		Container.style.width = cw + 'px';

		gameContainer.style.width = cw + 'px';
		
		ad.style.position = 'fixed';
		ad.style.width =  cw + 'px';
	
		if(screen.height <= 480) {
			gameStart.style.height = ch - 176 + 'px';
			var stImg = gameStart.getElementsByTagName('img');
			start1.style.width = cw + 'px';
			start1.style.height = start1.offsetHeight - 60 + 'px';
			btn.style.width = cw + 'px';
			btn.style.height = btn.offsetHeight - 5 + 'px';
			start2.style.width = cw + 'px';
			start2.style.height = start2.offsetHeight - 15 + 'px';
			
			Container.style.height = ch - bgt.offsetHeight - ad.offsetHeight + 'px';
			Container.style.top = -34 + 'px';
			gameContainer.style.height = ch - bgt.offsetHeight - ad.offsetHeight + 'px';
			gameContainer.style.top = -34 + 'px';
			ad.style.top = bgt.offsetHeight + gameContainer.offsetHeight  + 'px';

			bgt.style.width = cw +'px';		
			bgt.style.height = bgt.offsetHeight - 40 +'px';		
		}
		else {
			gameStart.style.height = ch + 'px';
			Container.style.height = ch - bgt.offsetHeight - ad.offsetHeight - mtop + 'px';
			// Container.style.paddingTop = mtop + 'px';
			gameContainer.style.height = ch - bgt.offsetHeight - ad.offsetHeight - mtop + 'px';
			// gameContainer.style.paddingTop = mtop + 'px';
		}
	}

	GameApp.init();

})();